<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form v-loading="formLoading" :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="部门类型" prop="type">
        <el-radio-group v-model="dataForm.type">
          <el-radio  :label="0" >普通部门</el-radio>
          <el-radio  :label="1" >田基地</el-radio>
        </el-radio-group>
      </el-form-item>
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="dataForm.name" placeholder="部门名称"></el-input>
    </el-form-item>
    <el-form-item label="上级部门" prop="parentId">
      <el-input v-model="dataForm.parentName" placeholder="点击选择上级部门" v-popover:deptListPopover :readonly="true" class="menu-list__input"></el-input>
        <el-popover ref="deptListPopover" placement="bottom-start" trigger="click">
          <el-tree
            ref="deptListTree" node-key="id" 
            show-checkbox
            :data="deptList" 
            :props="deptListTreeProps"
            @check-change="checkChange"
            :check-strictly="true" 
            :default-expand-all="true"
            :highlight-current="true" 
            :expand-on-click-node="false"
          >
          </el-tree>
        </el-popover>
    </el-form-item>
    <el-form-item label="部门编号" prop="code">
      <el-input v-model="dataForm.code" placeholder="部门编号"></el-input>
    </el-form-item>
    <el-form-item v-if="dataForm.type==1" label="地址" prop="address">
      <el-input type="textarea" v-model="dataForm.address" placeholder="地址"></el-input>
    </el-form-item>
    <el-form-item v-show="dataForm.type==1" label="现场图片" prop="liveImage">
      <singleFileUpload ref="singleFileUploadRef"></singleFileUpload>
      <img v-if="dataForm.liveImage" :src="loadImage(dataForm.liveImage)" 
        @click="downloadFile(dataForm.liveImage)" height="100px" style="max-width:100%;overflow:hidden">
        <iframe v-show="false" :src="ifrUrl"></iframe>
    </el-form-item>
    <el-form-item label="状态" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio  :label="0" >禁用</el-radio>
          <el-radio  :label="1" >启用</el-radio>
        </el-radio-group>
      </el-form-item>
    <el-form-item label="排序" prop="orderNum">
      <el-input-number v-model="dataForm.orderNum" controls-position="right" :min="0" label="排序号"></el-input-number>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" v-loading="formLoading" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { treeDataTranslate } from '@/utils'
  import singleFileUpload from '@/components/single-file-upload/index'
  export default {
    data () {
      return {
        visible: false,
        formLoading:false,
        dataForm: {
          id: 0,
          parentId: '',
          name: '',
          orderNum: '',
          code: '',
          status: 0,
          type: 0,
          parentName: '',
          address: '',
          liveImage: '',
        },
        ifrUrl:'',
        dataRule: {
          parentId: [
            { required: true, message: '上级部门不能为空', trigger: 'change' }
          ],
          name: [
            { required: true, message: '部门名称不能为空', trigger: 'blur' }
          ],
          orderNum: [
            { required: true, message: '排序不能为空', trigger: 'blur' }
          ],
          code: [
            { required: true, message: '部门编号不能为空', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '状态不能为空', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '部门类型不能为空', trigger: 'blur' }
          ],
        },
        deptList: [],
        deptListTreeProps: {
          label: 'name',
          children: 'children',
          disabled: function(data, node){
            return data.type != 1 ? false :true
          }
        }
      }
    },
    components: {
      singleFileUpload
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0

        // 初始化部门树
        this.$http({
          url: this.$http.adornUrl('/sys/dept/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.deptList = treeDataTranslate(data.deptList, 'id')
        }).then(() => {
          this.visible = true
          this.formLoading = false
          this.$nextTick(() => {
            this.$refs['singleFileUploadRef'].clearHistory()
            this.$refs['dataForm'].resetFields()

            if (this.dataForm.id) {
              this.$http({
                url: this.$http.adornUrl(`/sys/dept/info/${this.dataForm.id}`),
                method: 'get',
                params: this.$http.adornParams()
              }).then(({data}) => {
                if (data && data.code === 0) {
                  this.dataForm.parentId = data.dept.parentId
                  this.dataForm.name = data.dept.name
                  this.dataForm.orderNum = data.dept.orderNum
                  this.dataForm.code = data.dept.code
                  this.dataForm.status = data.dept.status
                  this.dataForm.type = data.dept.type
                  this.dataForm.address = data.dept.address
                  this.dataForm.liveImage = data.dept.liveImage
                  this.dataForm.liveImage = data.dept.liveImage
                  this.dataForm.version = data.dept.version
                  this.deptListTreeSetCurrentNode()
                }
              })
            }
          })
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid && !this.formLoading) {
            this.formLoading = true
            this.$http({
              url: this.$http.adornUrl(`/sys/dept/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'parentId': this.dataForm.parentId,
                'name': this.dataForm.name,
                'orderNum': this.dataForm.orderNum,
                'code': this.dataForm.code,
                'status': this.dataForm.status,
                'type': this.dataForm.type,
                'address': this.dataForm.address,
                'version': this.dataForm.version,
                'liveImage': this.$cookie.get('uploadFileId') || this.dataForm.liveImage
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })

                this.$refs['singleFileUploadRef'].clearHistory()
              } else {
                this.formLoading = false
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 菜单树设置当前选中节点
      deptListTreeSetCurrentNode () {
        this.$refs.deptListTree.setChecked(this.dataForm.parentId,true,false)
        this.dataForm.parentName = (this.$refs.deptListTree.getCheckedNodes() || [])[0].name
      },
      // 节点修改
      checkChange(data, checked, node){
          if(checked == true){// 选中部门
              this.checkedId = data.id;
              this.$refs.deptListTree.setCheckedNodes([data]);

              this.dataForm.parentId = data.id
              this.dataForm.parentName = data.name
          }
      },
      nodeClick(data,checked,node){
          this.checkedId = data.id
          this.$refs.deptListTree.setCheckedNodes([data]);
      },
      loadImage(bytearrayId){
          return this.$http.adornUrl('/fileAction/loadFile?bytearrayId='+bytearrayId+'&token='+ this.$cookie.get('token'))
      },
      downloadFile(bytearrayId){
        this.ifrUrl =''
         if(bytearrayId != "" || bytearrayId != null){
            this.$nextTick(() => {
              this.ifrUrl= this.$http.adornUrl('/fileAction/downloadFile?bytearrayId='+bytearrayId+'&token='+ this.$cookie.get('token'))
            })
         }
      },
    }
  }
</script>
